package com.chinawu.cloud.ss.config.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Collection;

/**
 * <p class="detail">
 * 功能：单分片精确分片算法-时间分片
 * </p>
 *
 * @author wuyubin
 * @version V1.0
 * @ClassName: PreciseTimeShardingAlgorithm
 * @date 2021年07月28日 14:00
 */
public class PreciseTimeShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    private Logger LOGGER = LoggerFactory.getLogger(PreciseTimeShardingAlgorithm.class);
    // 分隔符
    private static final String SEPARATOR = "_";

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        LOGGER.info("[单分片键精确分片算法]逻辑表:{},分片键:{},分片键值:{}",preciseShardingValue.getLogicTableName(),preciseShardingValue.getColumnName(),preciseShardingValue.getValue());
        // 分片键
        String columnName = preciseShardingValue.getColumnName();
        // 表分表后缀名称
        String tableNameSuffix = "";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        if ("create_time".equals(columnName)) {
            Long creeateTime =  preciseShardingValue.getValue();
            if (creeateTime != null) {
                tableNameSuffix = sdf.format(creeateTime);
            }
        }

        
        // 当配置actual-data-nodes=ds.tb_platform_money_record_$->{['202011','202012','202101']}
        // 输出 tb_platform_money_record_202011,tb_platform_money_record_202012,tb_platform_money_record_202101 采用方案一
        // 当配置actual-data-nodes=ds.tb_platform_money_record
        // 输出 tb_platform_money_record 采用方案二
        // 方案一
        for (String tableName : collection) {
            LOGGER.info("[单分片键精确分片算法]配置项表信息:{}",tableName);
            if (tableName.endsWith(tableNameSuffix)) {
                return tableName;
            }
        }
        // 方案二
        if (tableNameSuffix != null && !"".equals(tableNameSuffix)) {
            return preciseShardingValue.getLogicTableName() + SEPARATOR + tableNameSuffix;
        }
        // no table route info
        return null;
    }

}
